import 'dart:io';

import 'package:casdon/core/utils/wifi/wifi_name_monitor.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wifi_info_flutter/wifi_info_flutter.dart';

// 不监听，只是简单的获取当前wifi名称，
class WifiUtils {
  static WifiUtils? _instance;

  // 私有构造函数
  WifiUtils._();

  // 单例模式
  static WifiUtils getInstance() {
    _instance ??= WifiUtils._();
    return _instance!;
  }

  Future<WifiSsidResult> getCurrentWifiSsidResult() async {
    if (!(Platform.isAndroid || Platform.isIOS)) {
      return const WifiSsidResult(ssid: null, hasPermission: true);
    }

    final granted = await _ensureLocationPermission();
    if (!granted) {
      final permStatus = Platform.isIOS
          ? await Permission.locationWhenInUse.status
          : await Permission.location.status;
      return WifiSsidResult(
        ssid: null,
        hasPermission: false,
        permanentlyDenied: permStatus.isPermanentlyDenied,
      );
    }

    final name = await WifiInfo().getWifiName();
    return WifiSsidResult(
      ssid: _sanitizeWifiName(name),
      hasPermission: true,
    );
  }

  String? _sanitizeWifiName(String? name) {
    if (name == null) return null;
    if (name.isEmpty) return null;
    if (name == '<unknown ssid>') return null;
    if (name == 'null') return null;
    return name;
  }

  Future<bool> _ensureLocationPermission() async {
    PermissionStatus status = Platform.isIOS
        ? await Permission.locationWhenInUse.status
        : await Permission.location.status;

    if (status.isGranted || status.isLimited) {
      return true;
    }
    // 可能不是拒绝，而是没有请求过该权限，所以需要主动请求一次
    status = Platform.isIOS
        ? await Permission.locationWhenInUse.request()
        : await Permission.location.request();

    if (status.isGranted || status.isLimited) {
      return true;
    }

    if (status.isDenied && Platform.isAndroid) {
      // Android 再检查一次通用 location
      final fallback = await Permission.location.status;
      if (fallback.isGranted) return true;
      final retry = await Permission.location.request();
      if (retry.isGranted) return true;
    }

    return false;
  }

  /// 原方法保留，便于向下兼容：无权限时抛出异常
  Future<String?> getCurrentWifiSSid() async {
    final result = await getCurrentWifiSsidResult();
    if (!result.hasPermission) throw const WifiPermissionException();
    return result.ssid;
  }
}

class WifiSsidResult {
  final String? ssid;
  final bool hasPermission;
  final bool permanentlyDenied;
  const WifiSsidResult({
    required this.ssid,
    required this.hasPermission,
    this.permanentlyDenied = false,
  });
}
